package com.ywj.chatroom.multiroom.server.handler;

import com.ywj.chatroom.multiroom.message.ChatRequestMessage;
import com.ywj.chatroom.multiroom.message.ChatResponseMessage;
import com.ywj.chatroom.multiroom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 好友聊天信息处理器
 * 1.拿到好友姓名； 2.通过好友姓名查出channel
 * 3.发送消息     4.如果对方不在线就响应对方不在线告诉自己
 */
@ChannelHandler.Sharable
public class ChatRequestHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
       //发给谁
       String to = msg.getTo();

       //找到channel
       Channel channel = (Channel) SessionFactory.getSession().getChannel(to);
       //对方在线
       if(channel != null){
//           ctx.writeAndFlush(msg.getContent());    自己写
           ctx.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
       }
       //对方不在线
       else{
           ctx.writeAndFlush(new ChatResponseMessage(false, "对方用户不在线"));
       }
    }
}
